package com.gu.interceptor;

import com.gu.entity.UserDO;
import com.gu.utils.CookieUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {


    /**
     * controller方法执行前运行
     * @param request
     * @param response
     * @param handler  通过反射的方式反射到请求地址所对应的方法，打印结果为
     *                 com.neutech.controller.EmpController#empList(Integer, Integer, ModelMap)
     *                 这个对象指向这个方法
     * @return
     * @throws Exception
     */


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");


        if (CookieUtils.cookies2Map(request.getCookies()).get("token") == null) {
            response.sendRedirect("/user/loginView");
            return false;
        }

        String token = (String) request.getServletContext().getAttribute("token");

        if (token.equals(CookieUtils.cookies2Map(request.getCookies()).get("token"))){
            return true;
        }else {
            response.sendRedirect("/user/loginView");
            return false;
        }
    }

    /**
     * controller 方法执行完，controller方法执行结果处理前执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
